package com.lapi.lapiclientsdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.lapi.lapiclientsdk.model.User;

import java.util.HashMap;
import java.util.Map;

import static com.lapi.lapiclientsdk.utils.SignUtils.genSign;

/**
 * 调用第三方接口的客户端
 *
 * @author wzhdjy
 */
//  参考文档：https://hutool.cn/docs/#/http/Http%E5%AE%A2%E6%88%B7%E7%AB%AF%E5%B7%A5%E5%85%B7%E7%B1%BB-HttpUtil
public class LApiClient {
    String BASE_URL = "http://localhost:8123/api/";

    private String accessKey;
    private String secretKey;

    public LApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    public String getNameByGet(String name) {
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        //将"name"参数添加到映射中
        paramMap.put("name", name);
        String result = HttpUtil.get(BASE_URL + "name/", paramMap);
        System.out.println("——————————————");
        System.out.println(result);
        return result;
    }

    public String getNameByPost(String name) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        String result = HttpUtil.post(BASE_URL + "name/", paramMap);
        System.out.println("——————————————");
        System.out.println(result);
        return result;
    }

    public String getUserNameByPost(User user) {

        String userJson = JSONUtil.toJsonStr(user);
//        restful接口使用HttpRequest工具类进行请求
        HttpResponse response = HttpRequest.post(BASE_URL + "name/josn/")
                .body(userJson)
                .addHeaders(getHeaderMap(userJson))
                .execute();
        System.out.println("——————————————response：");
//        response是请求结果
        System.out.println(response);
//        状态码
        int status = response.getStatus();
//        返回数据
        String result = response.body();
        System.out.println(result);
        return result;
    }

    private Map<String, String> getHeaderMap(String body) {
        HashMap<String, String> headerMap = new HashMap<>();
        headerMap.put("accessKey", accessKey);
//        因为密钥不能进行明文传输，下面进行加密
//        headerMap.put("secretKey",secretKey);
//        加入随机数
        String nonce = RandomUtil.randomNumbers(4);
        headerMap.put("nonce", nonce);
//        加入时间戳
        headerMap.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        headerMap.put("body", body);
        headerMap.put("sign", genSign(body, secretKey));
        return headerMap;
    }
}
